package top.yudoge.dogeeditorserverj.stores;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Primary
@Component
public class InMemoryCache implements Cache {

    public Map<String, Object> cache = new HashMap<>();

    @Override
    public boolean exists(String key) {
        return cache.containsKey(key);
    }

    @Override
    public synchronized void put(String key, Object value) {
        this.cache.put(key, value);
    }

    @Override
    public synchronized <T> T get(String key, Class<T> clz) {
        Object o = this.cache.get(key);
        if (o == null) {return null;}
        if (!clz.isAssignableFrom(o.getClass())) {
            throw new IllegalArgumentException("Class " + clz.getName() + " is not assignable from " + o.getClass().getName());
        }
        return clz.cast(o);
    }

    @Override
    public synchronized void invalidate(String key) {
        cache.remove(key);
    }

}
